package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.mapper.MenuMapper;
import com.example.demo.mapper.MenuMetaMapper;
import com.example.demo.entity.MenuEntity;
import com.example.demo.entity.MenuMetaEntity;
import com.example.demo.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private MenuMetaMapper menuMetaMapper;

    public List<MenuEntity> findChildrenMenus(Integer parentId) {
        List<MenuEntity> children = menuMapper.selectByParentId(parentId);
        for (MenuEntity child : children) {
            //meta
            MenuMetaEntity menuMeta = findMenuMeta(child.getId());
            child.setMeta(menuMeta);
            // 递归查找子菜单
            child.setChildren(findChildrenMenus(child.getId()));
        }
        return children.isEmpty() ? null : children;
    }

    public MenuMetaEntity findMenuMeta(Integer menuId) {
        LambdaQueryWrapper<MenuMetaEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MenuMetaEntity::getMenuId, menuId);
        MenuMetaEntity menuMetaEntity = menuMetaMapper.selectOne(wrapper);
        return menuMetaEntity;
    }

    @Override
    public List<MenuEntity> findByUserId(Integer userId) {

        //todo 应该用userid 关联用户权限


        List<MenuEntity> menuEntities = menuMapper.selectOneList();
        for (MenuEntity entity : menuEntities) {
            MenuMetaEntity menuMeta = findMenuMeta(entity.getId());
            entity.setMeta(menuMeta);
            //递归查子菜单
            List<MenuEntity> childrenMenus = findChildrenMenus(entity.getId());
            entity.setChildren(childrenMenus);

        }

        return menuEntities;
    }
}
